package com.example.streaming;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author lbq
 * @version 1.0
 * @date 2022/3/14 22:45
 */
public class WordCountStreaming {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        final DataStreamSource<String> stream = env.socketTextStream("aliyun", 7777, "\n");
        final SingleOutputStreamOperator<Tuple2<String, Integer>> tuple2SingleOutputStreamOperator = stream.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String line, Collector<Tuple2<String, Integer>> collector) throws Exception {
                final String[] words = line.split("\\s+");
                for (String word : words) {
                    collector.collect(new Tuple2<>(word, 1));
                }
            }
        });

        final SingleOutputStreamOperator<Tuple2<String, Integer>> result = tuple2SingleOutputStreamOperator.keyBy(0).sum(1);

        result.setParallelism(1).print();

        env.execute(WordCountStreaming.class.getName());

    }
}
